<template>
  <div>
    <searchBox @handleSearch="handleSearch" @handleReset="handleQuery">
      <el-form :model="queryParams.param" ref="siteProductForm" :inline="true">
        <el-form-item label="分类名称" prop="name">
          <el-input
            v-model.trim="queryParams.param.name"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            style="width: 200px"
            v-model="queryParams.param.status"
            placeholder="请选择"
            clearable
          >
            <el-option
              v-for="dict in sys_status_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
    </searchBox>
    <el-button type="primary" @click="router.back()">返回</el-button>
    <el-button type="primary" @click="publicSiteAdd(1)">新增</el-button>
    <el-table
      :data="siteProductList"
      row-key="id"
      style="height: calc(100vh - 300px)"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="ID" prop="id" width="100" />
      <el-table-column label="站点分类名称">
        <template #default="scope">
          <el-space spacer=" ">
            <el-text>{{ scope.row.name }}</el-text>
            <el-button type="primary" @click="viewTranslate(1, scope.row)"
              >查看翻译</el-button
            >
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="分类名称">
        <template #default="scope">
          <el-space spacer=" ">
            <el-text>{{ scope.row.productCategoryName }}</el-text>
            <el-button type="primary" @click="viewTranslate(0, scope.row)"
              >查看翻译</el-button
            >
          </el-space>
        </template>
      </el-table-column>
      <el-table-column label="排序" prop="seq" align="center" />
      <el-table-column label="状态" align="center">
        <template #default="scope">
          <el-switch
            :width="58"
            class="demo"
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="关闭"
            inline-prompt
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="publicSiteAdd(0, scope.row)"
            >编辑</el-button
          >
          <el-button
            type="danger"
            link
            @click="handleControls(scope.row)"
            v-if="!scope.row.status"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <Pagination
      :total="total"
      :limit="queryParams.pageSize"
      :page="queryParams.pageNum"
      @pagination="handlePageChange"
    />
    <el-dialog
      v-model="dialogVisible"
      :title="newTitle"
      draggable
      width="35%"
      :before-close="handleServiceClose"
    >
      <el-form
        :model="siteProductFrom"
        ref="siteProductRef"
        :rules="siteProductRules"
      >
        <el-form-item label="上级节点" prop="fatherId" required>
          <el-tree-select
            v-model="siteProductFrom.fatherId"
            :data="fatherList"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="分类节点" prop="productCategoryId" required>
          <el-tree-select
            v-model="siteProductFrom.productCategoryId"
            :data="sortList"
            :props="treeProps"
            value-key="id"
            placeholder="请选择"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="分类排序" prop="seq" required>
          <el-input
            type="number"
            v-model.trim="siteProductFrom.seq"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="当前状态"
          style="width: 100%"
          prop="status"
          required
        >
          <el-switch
            :width="58"
            v-model="siteProductFrom.status"
            :active-value="1"
            :inactive-value="0"
            active-text="开启"
            inactive-text="关闭"
            inline-prompt
          />
        </el-form-item>
        <el-form-item prop="descriptions" required style="width: 100%">
          <MoreLanguage
            :newList="siteProductFrom.descriptions"
            label="名称"
            :showControls="true"
          ></MoreLanguage>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleServiceClose">取消</el-button>
        <el-button type="primary" @click="handleServiceSure"> 确定 </el-button>
      </template>
    </el-dialog>
    <Translation
      :dialogVisible="openViewTranslate"
      :languageList="translateData"
      @handleTranslationClose="handleTranslationClose"
    ></Translation>
  </div>
</template>
<script setup name="Brand">
import { ref, reactive, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
const { proxy } = getCurrentInstance();
const router = useRouter();
const route = useRoute();
const total = ref(0);
const siteProductList = ref([]);
const newTitle = ref(""); //名称
const publicItem = ref(""); //公共赋值对象
const openViewTranslate = ref(false);
const translateData = ref([]); //多语言数据

const dialogVisible = ref(false); //默认不显示弹窗
const sortList = ref([]); //分类数据
const fatherList = ref([]); //父级数据
const loading = ref(false);

onMounted(() => {
  getList();
  getLanguage();
});
const getList = () => {
  // product.general.websiterawcategoryList({
  //   data: {
  //     pageNum: 0,
  //     pageSize: 0
  //   }
  // })
  queryParams.value.param.websiteId = Number(route.query.id);
  queryParams.value.param.languageId = Number(route.query.languageId);
  site.general
    .sitecategoryList({
      data: queryParams.value,
    })
    .then((res) => {
      siteProductList.value = res.data;
      total.value = res.total;
      loading.value = true;
    });
};
const handleServiceSure = () => {
  proxy.$refs["siteProductRef"].validate((valid) => {
    if (!valid) return;
    if (!proxy.publicArray(siteProductFrom.value.descriptions))
      return proxy.$modal.msgError("请完整填写");
    siteProductFrom.value.websiteId = Number(route.query.id);
    // return
    if (newTitle.value === "新增") {
      site.general
        .sitecategoryAdd({
          data: siteProductFrom.value,
        })
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("添加成功");
            handleServiceClose();
            getList();
          }
        });
    } else {
      site.general
        .sitecategoryUpdate({
          pathParams: {
            id: publicItem.value.id,
          },
          data: siteProductFrom.value,
        })
        .then((res) => {
          if (res.code === 200) {
            proxy.$modal.msgSuccess("修改成功");
            handleServiceClose();
            getList();
          }
        });
    }
  });
};

const getLanguage = () => {
  // 获取基础信息数据
  site.general
    .sitewebsiteGetbyid({
      pathParams: {
        id: route.query.id,
      },
    })
    .then((res) => {
      siteProductFrom.value.descriptions = [];
      res.data.languageIds.forEach((e) => {
        siteProductFrom.value.descriptions.push({
          languageId: e,
          name: "",
        });
      });
      // console.log(   res.data.currencyId, "[[[]]]");
    });

  product.productcategory
    .productcategoryGetcategories({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          languageId: 1
        },
      },
    })
    .then((response) => {
      sortList.value = response.data;
    });
};
const handleSearch = () => {
  getList();
};
const handleQuery = () => {
  proxy.resetForm("siteProductForm");
  getList();
};
// 分页
const handlePageChange = (newPage) => {
  searchFrom.value.pageNum = newPage.page;
  searchFrom.value.pageSize = newPage.limit;
  getList();
};
// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  param: {
    websiteId: null,
    languageId: null,
    fatherId: 0,
    name: "", //分类名称
  },
});

const siteProductFrom = ref({
  productCategoryId: null, //分类名称
  status: 1,
  websiteId: null,
  seq: 0,
  fatherId: null,
  descriptions: [],
});

const { sys_status_type } = proxy.useDict("sys_status_type");
const publicSiteAdd = (index, rowItem) => {
  TreeList(index, rowItem);
};
const handleServiceClose = () => {
  proxy.resetForm("siteProductRef");
  dialogVisible.value = false;
  siteProductFrom.value.productCategoryId = null;
  siteProductFrom.value.status = 1;
  siteProductFrom.value.websiteId = null;
  siteProductFrom.value.seq = 0;
  siteProductFrom.value.fatherId = null;
  siteProductFrom.value.descriptions = [];
};
// 表格状态控制
const handleStatusChange = (e) => {
  // if (!loading.value) return;
  proxy.$modal
    .confirm("是否确认修改此数据的状态？")
    .then(() => {
      return site.general
        .sitecategoryUpdatestatus({
          pathParams: {
            id: e.id,
          },
          params: {
            status: e.status,
          },
        })
        .then((response) => {
          proxy.$modal.msgSuccess("修改状态成功");
          getList();
        });
    })
    .catch(() => {
      if (e.status) {
        return (e.status = 0);
      } else {
        return (e.status = 1);
      }
    });
};
const getDetails = () => {
  site.general
    .sitecategoryGetbyid({
      pathParams: {
        id: publicItem.value.id,
      },
    })
    .then((res) => {
      newTitle.value = "编辑";
      dialogVisible.value = true;
      siteProductFrom.value.descriptions = [];
      siteProductFrom.value.productCategoryId = res.data.productCategoryId;
      siteProductFrom.value.status = res.data.status;
      siteProductFrom.value.seq = res.data.seq;
      res.data.descriptions.forEach((e) => {
        siteProductFrom.value.descriptions.push({
          languageId: e.languageId,
          name: e.name,
        });
      });
      siteProductFrom.value.fatherId = res.data.fatherId;
      console.log(res.data);
    });
};
const TreeList = (index, rowItem) => {
  site.general
    .sitecategoryList({
      data: {
        pageNum: 1,
        pageSize: 999,
        param: {
          websiteId: Number(route.query.id),
          languageId: Number(route.query.languageId),
        },
      },
    })
    .then((res) => {
      const uniqueItems = new Map();
      let newList = [{ name: "顶级节点", id: 0 }];
      [newList, res.data].flat().forEach((item) => {
        if (!uniqueItems.has(item.id)) {
          uniqueItems.set(item.id, item);
        }
      });
      fatherList.value = Array.from(uniqueItems.values());
      console.log(fatherList.value);
      if (index) {
        publicItem.value = {};
        dialogVisible.value = true;
        newTitle.value = "新增";
        siteProductFrom.value.fatherId = 0;
        getLanguage();
      } else {
        publicItem.value = rowItem;
        getDetails();
      }
    });
};
const handleControls = (row) => {
  proxy.$modal.confirm("是否确认删除此数据项？").then(function () {
    return site.general
      .sitecategoryDeletebatch({
        data: {
          ids: [row.id],
        },
      })
      .then((res) => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      });
  });
};
const siteProductRules = reactive({
  seq: [
    { required: true, message: "请输入", trigger: "blur" },
    {
      pattern: /^(?:0|[1-9]\d*)$/,
      message: "只能允许正整数",
      trigger: "blur",
    },
  ],
  productCategoryId: [{ required: true, message: "请选择", trigger: "blur" }],
  descriptions: [{ required: true, message: "请输入", trigger: "blur" }],
});
// 自定义 props
const treeProps = {
  label: "name",
  value: "id",
  children: "children",
  disabled: (data) => {
    return data.status ? false : true;
  },
};
const viewTranslate = (index, rowItem) => {
  if (index) {
    site.general
      .sitecategoryGetbyid({
        pathParams: {
          id: rowItem.id,
        },
      })
      .then((res) => {
        openViewTranslate.value = true;
        translateData.value = res.data.descriptions;
      });
  } else {
    product.productcategory
      .productcategoryGetbyid({
        pathParams: {
          id: rowItem.productCategoryId,
        },
      })
      .then((response) => {
        openViewTranslate.value = true;
        translateData.value = response.data.categoryDescriptionList;
      });
  }
};
const handleTranslationClose = () => {
  openViewTranslate.value = false;
};
</script>
